<?php
function loadModule($module, $params = array())
{
    global $_user, $_session;

    if ($params)
    {
        extract($params);
    }

    $content = '';
    if (file_exists($module_file = MODULE_PATH . $module . '.php'))
    {
        ob_start();
        include $module_file;
        $content = ob_get_contents();
        ob_end_clean();
    }
    return $content;
}

function module($module, $params = array(), $cache_name = '', $expire = -1)
{
    if (! $cache_name)
        $cache_name = $module;

    $content = '';
    if ($expire < 0)
    {
        // no cache need
        $content = loadModule($module, $params);
    }
    else
    {
        // need cache for expire time
        if (! ($content = cache('cache:' . $cache_name)))
        {
            // no cache or cache expire out
            $content = loadModule($module, $params);

            cache('cache:' . $cache_name, $content, $expire);
        }
    }
    return $content;
}

function site_url($var=NULL) {
    if($var==NULL){
        return SITE_URL;
    }else{
        $var = trim($var,'/');
        return SITE_URL.$var;
    }
}

function e($s){
    echo $s,'<br/>';
}

function l($info, $file = 'info')
{
    $debug = debug_backtrace();
    if (count($debug) > 1)
        $debug = $debug[1];
    else
        $debug = $debug[0];

    $time = date('Y-m-d H:i:s');
    $ip = $_SERVER['REMOTE_ADDR'];
    $url = $_SERVER['REQUEST_URI'];
    $file_name = $debug['file'];
    $line = $debug['line'];
    $function = $debug['function'];
    $info = is_string($info) ? $info : var_export($info, true);

    $server_addr = $_SERVER['SERVER_ADDR'];

    $str = 'Time:' . $time . ', ' .
           'Server:' . $server_addr . ', ' .
           'IP:' . $ip . ', ' .
           'URL:' . $url . ', ' .
           'File:' . $file_name . ', ' .
           'Line:' . $line . ', ' .
           'Function:' . $function . ', ' .
           'Info:' . $info . "\n";
    file_put_contents(LOG_PATH . $file . '.log', $str, FILE_APPEND);
}

function return_ip()
{
   $ip = "-1";
   if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
   {
        $ip_a = explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']) ;
        for($i=0;$i<count($ip_a);$i++)
        {//
            $tmp = trim($ip_a[$i]) ;
            if($tmp=='unknown'||$tmp=='127.0.0.1'||strncmp($tmp,'10.',3)==0||strncmp($tmp,'172',3)==0||strncmp($tmp,'192',3)==0)
                continue ;
            $ip = $tmp;
            break ;
        }
   }
   else if(!empty($_SERVER['HTTP_CLIENT_IP']))
   {
        $ip = trim($_SERVER['HTTP_CLIENT_IP']);
   }
   else if (!empty($_SERVER['REMOTE_ADDR']))
   {
        $ip = trim($_SERVER['REMOTE_ADDR']);
   }
   else
   {
        $ip = "-1";
   }
   return $ip;
}

function p($info, $exit = true, $ret = false)
{
    if (defined('RUNNING_MODE') && RUNNING_MODE == 'dev')
    {
        $debug = debug_backtrace();

        $output = '';
        $output .= '<b>File</b>:' . $debug[0]['file'] . '<br/>';
        $output .= '<b>Line</b>:' . $debug[0]['line'] . '<br/>';
        $output .= '<b>Info</b>:<br/>';
        $output .= '<pre>';
        $output .= var_export($info, true);
        $output .= '</pre>';

        if ($ret)
            return $ret;
        else
            echo $output;
        if ($exit)
            exit;
    }
    else
    {
        return;
    }
}

function curUrlName($str)
{
    $cur_url_array = explode('.',$str);
    $cur_url_name = str_replace("/","",$cur_url_array[0]);
    return $cur_url_name;
}

//remove page val's url
//@caixudong 增加两个参数，第一个是手动传入的额外参数，第二个是否从URL删除分页参数，默认删除
function parse_cur_url($p = array(),$remove_page = true){

    //base url
    $base_name = '/' . basename($_SERVER['SCRIPT_FILENAME']);

    //ex url
//    $tmp_arr = $_GET + $_POST + $p;
    $tmp_arr = array_merge($_GET, $_POST, $p);
            // remove page
    if($remove_page) unset($tmp_arr['page']);
    if($tmp_arr)
        $ex_url = http_build_query($tmp_arr);
    else
        $ex_url = '';

    //full url
    if($ex_url)
        $full_url = $base_name."?".$ex_url;
    else
        $full_url = $base_name;

    return $full_url;
}
//截取中文字符
function cnSubStr($string,$sublen,$tip='')
{
    $len = strlen($string);
    if($sublen>=$len)
    {
        return $string;
    }
    $s="";
    for($i=0;$i<$sublen;$i++)
    {
        if(ord($string{$i})>127)
        {
            $s.=$string{$i}.$string{++$i};
            continue;
        }else{
            $s.=$string{$i};
            continue;
        }
    }

    if(strlen($s) >= $len)
        return $s;
    return $s.$tip;
}

//去除空格
function trim_space($s) {
	$s = mb_ereg_replace('^(　| )+', '', $s);
	$s = mb_ereg_replace('(　| )+$', '', $s);
	return $s;
}

//网页内容抓取 add by final
function curl_get_contents($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
//    curl_setopt($ch, CURLOPT_REFERER,_REFERER_);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    @curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACH, true);
    curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 86400); // 缓存一天
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}


// array_diff's bug for PHP5.2.6-5.3.3
function my_array_diff($a1, $a2)
{
    $a2 = array_flip((array)$a2);
    foreach ((array)$a1 as $key => $item)
    {
        if (isset($a2[$item]))
        {
            unset($a1[$key]);
        }
    }
    return $a1;
}

function d($info = null, $time = false)
{
    if (! DEBUG)
        return;
    static $debug_info = array();
    if ($info != 'get_debug_data')
    {
        $debug_info[] = array('info'=>$info, 'backtrace'=>debug_backtrace());
        if ($time)
            time_debug('debug_time_' . count($debug_info));
    }

    return $debug_info;
}

//去除空格判断空
function trim_empty($str,$is_zh = false){
    $str = $is_zh ? trim_space($str) : trim($str);
    return empty($str);
}
//获取HOST
function getHttpHost(){

    return "http://".(isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''));
}
//跳转
function redirect($uri = '/', $method = 'location', $http_response_code = 302)
{
    switch($method)
    {
        case 'refresh'	: header("Refresh:0;url=".$uri);
            break;
        default			: header("Location: ".$uri, TRUE, $http_response_code);
            break;
    }
    exit;
}

function rtxMessage($messages){
    foreach($messages as $v){
        $title = iconv('UTF-8','GBK',$v['title']);
        $message = iconv('UTF-8','GBK',$v['message']);
        $user_name = iconv('UTF-8','GBK',$v['user_name']);
        $rtx_notice = 'http://180.168.84.109:8012/sendnotify.cgi?delaytime=0&title='.$title.'&msg='.$message.'&receiver='.$user_name;
        //异步调用
//        $fp = fsockopen("180.168.84.109", 8012, $errno, $errstr, 30);
//        if (!$fp) {
//            echo "$errstr ($errno)<br />\n";
//        } else {
//            $out = "GET /sendnotify.cgi?delaytime=0&title=$title&msg=$message&receiver=$user_name / HTTP/1.1\r\n";
//            $out .= "Host: 180.168.84.109\r\n";
//            $out .= "Connection: Close\r\n\r\n";
//
//            fwrite($fp, $out);
//            /*忽略执行结果
//            while (!feof($fp)) {
//            echo fgets($fp, 128);
//            }*/
//            fclose($fp);
//        }
        file_get_contents($rtx_notice);
    }
}

/**
 * GET方式调用HTTP接口，含重试机制
 * @param $url 接口地址
 * @param int $max_num 重试次数
 * @param int $min_time 超时时间
 * @return mixed|string
 * @author yangzi
 */
function http_get_contents($url,$max_num = 1,$min_time = 1){
    $str = '';
    $i = 0;

    while(trim_empty($str) && $i<$max_num){
        $str = curl_get_contents($url,$min_time);
        $i++;
    }

    return $str;
}
/**
 * POST方式调用HTTP接口，含重试机制
 * @param $url 接口地址
 * @param array $param 参数
 * @param int $max_num 重试次数
 * @param int $min_time 超时时间
 * @return mixed|string
 * @author yangzi
 */
function http_post_contents($url,$param = array(),$max_num = 1,$min_time = 1){
    $str = '';
    $i = 0;

    while(trim_empty($str) && $i<$max_num){
        $str = curl_post_contents($url,$param,$min_time);
        $i++;
    }

    return $str;
}